package com.cucn.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cucn.commonutils.JwtUtils;
import com.cucn.commonutils.Result;
import com.cucn.eduorder.entity.Order;
import com.cucn.eduorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author KouChaoJie
 * @since 2021-10-13
 */
@RestController
//@CrossOrigin
@RequestMapping("/eduorder/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 生成订单方法,返回订单号
     *
     * @param courseId 课程id
     */
    @PostMapping("/createOrder/{courseId}")
    public Result saveOrder(@PathVariable String courseId, HttpServletRequest request) {
        //传入课程id,从request中得到token值,从token值中逆推出用户id
        //创建订单,返回订单号
        String orderNo = orderService.createOrders(courseId, JwtUtils.getMemberIdByJwtToken(request));

        return Result.ok().data("orderId", orderNo);
    }

    /**
     * 根据订单id查询订单信息
     *
     * @param orderId 订单号
     * @return 订单信息
     */
    @GetMapping("/getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        Order order = orderService.getOne(wrapper);

        return Result.ok().data("item", order);
    }

    /**
     * 根据课程id和用户id查询订单表中订单状态
     *
     * @param courseId 课程id
     * @param memberId 用户id
     * @return 已经支付true未支付false
     */
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        //支付状态,1已经支付
        wrapper.eq("status", 1);

        return orderService.count(wrapper) > 0;
    }
}

